/**
 * Copyright 2013-2015
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */	  

package com.ahrhyj.common.utils;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;

/**
 * AES 128bit 加密解密工具类
 * <p/>
 * 
 * @author <a href="mailto:durbao@126.com">durbao</a>
 * @version  Date: 2018年10月23日 下午3:05:18
 * @serial 1.0
 * @since 2018年10月23日 下午3:05:18
 */

public class AesEncryptUtil {
    
    //使用AES-128-CBC加密模式，key需要为16位,key和iv可以相同！
    private static String KEY = "nmlt20181023java";
    
    private static String IV = "nmlt20181023wxcx";
    
    
    /**
     * 加密方法
     * @param data  要加密的数据
     * @param key 加密key
     * @param iv 加密iv
     * @return 加密的结果
     * @throws Exception
     */
    public static String encrypt(String data, String key, String iv) throws Exception {
        try {

            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");//"算法/模式/补码方式"
            int blockSize = cipher.getBlockSize();

            byte[] dataBytes = data.getBytes();
            int plaintextLength = dataBytes.length;
            if (plaintextLength % blockSize != 0) {
                plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
            }

            byte[] plaintext = new byte[plaintextLength];
            System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);

            SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
            IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());

            cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
            byte[] encrypted = cipher.doFinal(plaintext);

            return new Base64().encodeToString(encrypted);

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 解密方法
     * @param data 要解密的数据
     * @param key  解密key
     * @param iv 解密iv
     * @return 解密的结果
     * @throws Exception
     */
    public static String desEncrypt(String data, String key, String iv) throws Exception {
        try {
            byte[] encrypted1 = new Base64().decode(data);

            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
            SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
            IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());

            cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);

            byte[] original = cipher.doFinal(encrypted1);
            String originalString = new String(original);
            return originalString;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    /**
     * 使用默认的key和iv加密
     * @param data
     * @return
     * @throws Exception
     */
    public static String encrypt(String data) throws Exception {
        return encrypt(data, KEY, IV);
    }
    
    /**
     * 使用默认的key和iv解密
     * @param data
     * @return
     * @throws Exception
     */
    public static String desEncrypt(String data) throws Exception {
        return desEncrypt(data, KEY, IV);
    }
    
    /**
     * 使用默认的key和iv加密
     * @param data
     * @return
     * @throws Exception
     */
    public static String encrypt64(String data, String key, String iv) throws Exception {
        return encryptBASE64(AES_CBC_Encrypt(data.getBytes(), key.getBytes(), iv.getBytes())); 
    }
    
    /**
     * 使用默认的key和iv解密
     * @param data
     * @return
     * @throws Exception
     */
    public static String desEncrypt64(String data, String key, String iv) throws Exception {
    	return byteToString(AES_CBC_Decrypt(decryptBASE64(data), key.getBytes(), iv.getBytes()));
    }
    
    
    /**
     * 使用默认的key和iv加密
     * @param data
     * @return
     * @throws Exception
     */
    public static String encrypt64(String data) throws Exception {
        return encryptBASE64(AES_CBC_Encrypt(data.getBytes(), KEY.getBytes(), IV.getBytes())); 
    }
    
    /**
     * 使用默认的key和iv解密
     * @param data
     * @return
     * @throws Exception
     */
    public static String desEncrypt64(String data) throws Exception {
    	return byteToString(AES_CBC_Decrypt(decryptBASE64(data), KEY.getBytes(), IV.getBytes()));
    }
    
    
    
    /**
    * 测试
    */
    public static void main(String args[]) throws Exception {

        String test = "group2/M00/00/00/wKgLNV9tldeAUiovAACkp6SgOco825.jpg";

        String data = null;

        data = encrypt(test, KEY, IV);

        System.out.println(data);
        System.out.println(desEncrypt(data, KEY, IV));
   
		//加密
		String encrypted = encrypt64(test, "BeNsoQV7tbeaC0qp", "Sxpn0nkVUehsDg6q"); 
		//解密
		String decrypted = desEncrypt64(encrypted, "BeNsoQV7tbeaC0qp", "Sxpn0nkVUehsDg6q");
		
		System.out.println("加密后："+encrypted);
		System.out.println("urlEncoder加密后："+URLEncoder.encode(encrypted, "UTF-8"));
		System.out.println("解密后："+decrypted);
		
		
		System.out.println("加密后："+encrypt64(decrypted, "a5049f54b8384e3b", "746324e568505120"));
		System.out.println("解密后："+desEncrypt64(encrypt64(decrypted, "a5049f54b8384e3b", "746324e568505120"), "a5049f54b8384e3b", "746324e568505120"));
    
    }
    
    
    
	
	public static String byteToString(byte[] byte1){  
        return new String(byte1);  
    }
	
	public static byte[] AES_CBC_Encrypt(byte[] content, byte[] keyBytes, byte[] iv){
		try {
			SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
			Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
			cipher.init(Cipher.ENCRYPT_MODE,key, new IvParameterSpec(iv));
			byte[] result = cipher.doFinal(content); 
			return result;
		} catch (Exception e) {
			System.out.println("exception:"+e.toString());
		}
		return null;
	}
	
	public static byte[] AES_CBC_Decrypt(byte[] content, byte[] keyBytes, byte[] iv){
		try {
			SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
			Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
			cipher.init(Cipher.DECRYPT_MODE,key, new IvParameterSpec(iv)); 
			byte[] result = cipher.doFinal(content);
			return result;
		} catch (Exception e) {
			System.out.println("exception:"+e.toString());
		}
		return null;
	}
	
	//字符串装换成base64
	public static byte[] decryptBASE64(String key) throws Exception {   
        return Base64.decodeBase64(key.getBytes());
    }
	//base64装换成字符串
	public static String encryptBASE64(byte[] key) throws Exception {   
        return new String(Base64.encodeBase64(key));
    }
}
